package com.blrs.service.project.info.impI;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.*;
import com.blrs.domain.vo.BusinessMainClassVo;
import com.blrs.mapper.*;

import com.blrs.system.mapper.SysDeptMapper;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.service.project.info.IProjectInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 项目信息业务层处理
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@Service
public class ProjectInfoServiceImpl implements IProjectInfoService {
    @Autowired
    private ProjectInfoMapper projectInfoMapper;
    @Autowired
    private ProjectPaymentMethodMapper projectPaymentMethodMapper;
    @Autowired
    private SubProjectInfoMapper subProjectInfoMapper;
    @Autowired
    private ProjectChangeMapper projectChangeMapper;
    @Autowired
    private ProjectStageMapper projectStageMapper;
    @Autowired
    private PurchasingMapper purchasingMapper;
@Autowired
private SelfBuiltProjectMapper selfBuiltProjectMapper;
   @Autowired
   private SysDeptMapper sysDeptMapper;

    //修改主项目信息 进行变更
    @Override
    public int updateProjectInfoChange(ProjectInfo projectInfo, String changNote) throws NoSuchFieldException, IllegalAccessException {
        int count = 0;
        //先获取原始数据
        ProjectInfo data = projectInfoMapper.selectProjectInfoByProjectId(projectInfo.getProjectId());
        //利用反射获取两个对象的差异属性有哪些 主项目
        Map<String, String> stringObjectMap = comparePurchasingProjectInfo(data, projectInfo);
        if (stringObjectMap.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : stringObjectMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key).append(":").append(value).append(",");
            }
            // 删除最后一个逗号
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            //变更内容
            ProjectChange projectChange = new ProjectChange();
            projectChange.setProjectType(0);
            projectChange.setChangedNote(projectInfo.getChangeNote());
            projectChange.setProjectId(projectInfo.getProjectId());
            projectChange.setProjectNumber(projectInfo.getProjectNumber());
            projectChange.setProjectName(projectInfo.getProjectName());
            projectChange.setChangedContent(sb.toString());//变更内容
            projectChange.setChangedTime(new Timestamp(new Date().getTime()));
            projectChange.setUserChangedId(SecurityUtils.getUserId().toString());
            projectChange.setUserChanged(SecurityUtils.getUsername());
            projectChange.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            projectChangeMapper.insertProjectChange(projectChange);
        }
        projectInfo.setOperateTime(new Timestamp(new Date().getTime()));
        projectInfo.setOperateName(SecurityUtils.getUsername());
        projectInfo.setOperateId(SecurityUtils.getUserId().toString());
        count = projectInfoMapper.updateProjectInfo(projectInfo);
        return count;
    }

    //主项目变更
    public Map<String, String> comparePurchasingProjectInfo(ProjectInfo purchasing, ProjectInfo purchasing1) throws NoSuchFieldException, IllegalAccessException {
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> changeMap = new HashMap<>();
        //purchasing = 原始数据 purchasing1=新传入的数据
        Field executorName = ProjectInfo.class.getDeclaredField("executorName");//执行人
        //Field executorId = ProjectInfo.class.getDeclaredField("executorId");
        Field startTime = ProjectInfo.class.getDeclaredField("startTime");
        Field endTime = ProjectInfo.class.getDeclaredField("endTime");
        changeMap.put("执行人", executorName);
        //changeMap.put("执行人id",executorId);
        changeMap.put("计划开始时间", startTime);
        changeMap.put("计划结束时间", endTime);
        for (Map.Entry<String, Object> entry : changeMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            Field field = (Field) value;
            field.setAccessible(true); // 设置访问权限为可访问
            Object value1 = field.get(purchasing);
            Object value2 = field.get(purchasing1);
            if (key.equals("计划开始时间")) {
                if (!value1.equals(value2)) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format((Date) value1);
                    String format1 = simpleDateFormat.format((Date) value2);
                    map.put(key, format + "变更为" + format1);
                }
            } else if (key.equals("计划结束时间")) {
                if (!value1.equals(value2)) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format((Date) value1);
                    String format1 = simpleDateFormat.format((Date) value2);
                    map.put(key, format + "变更为" + format1);
                }
            } else {
                // 比较属性值是否相等
                if ((value1 != null && value2 != null && !value1.equals(value2))) {
                    if (value1 instanceof BigDecimal) {
                        BigDecimal val1 = (BigDecimal) value1;
                        BigDecimal val2 = (BigDecimal) value2;
                        if (val1.compareTo(val2) != 0) {
                            map.put(key, value1 + "变更为" + value2);
                        }
                    } else {
                        map.put(key, value1 + "变更为" + value2);
                    }
                }
            }
        }
        return map;
    }

    @Override
    public int updateSubProjectInfoChange(SubProjectInfo subProjectInfo, String changNote) throws NoSuchFieldException, IllegalAccessException {
        int count = 0;
        //先获取原始数据
        SubProjectInfo data = subProjectInfoMapper.selectSubProjectInfoById(subProjectInfo.getId());
        //利用反射获取两个对象的差异属性有哪些 子项目
        Map<String, String> stringObjectMapSub = comparePurchasingSubProjectInfo(data, subProjectInfo);
        if (stringObjectMapSub.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : stringObjectMapSub.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key).append(":").append(value).append(",");
            }
            // 删除最后一个逗号
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            //变更内容
            ProjectChange projectChange = new ProjectChange();
            projectChange.setProjectType(1);
            projectChange.setChangedNote(subProjectInfo.getChangeNote());
            projectChange.setProjectId(subProjectInfo.getProjectId());
            projectChange.setProjectNumber(subProjectInfo.getProjectNumber());
            projectChange.setProjectName(subProjectInfo.getProjectName());
            projectChange.setChangedContent(sb.toString());//变更内容
            projectChange.setChangedTime(new Timestamp(new Date().getTime()));
            projectChange.setUserChangedId(SecurityUtils.getUserId().toString());
            projectChange.setUserChanged(SecurityUtils.getUsername());
            projectChange.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            projectChangeMapper.insertProjectChange(projectChange);
        }
        count = subProjectInfoMapper.updateSubProjectInfo(subProjectInfo);
        return count;
    }

    //子项目变更
    public Map<String, String> comparePurchasingSubProjectInfo(SubProjectInfo purchasing, SubProjectInfo purchasing1) throws NoSuchFieldException, IllegalAccessException {
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> changeMap = new HashMap<>();
        //purchasing = 原始数据 purchasing1=新传入的数据
        Field executorName = SubProjectInfo.class.getDeclaredField("executorName");//执行人
        Field cost = SubProjectInfo.class.getDeclaredField("cost");
        Field startTime = SubProjectInfo.class.getDeclaredField("startTime");
        Field endTime = SubProjectInfo.class.getDeclaredField("endTime");
        changeMap.put("执行人", executorName);
        changeMap.put("费用", cost);
        changeMap.put("计划开始时间", startTime);
        changeMap.put("计划结束时间", endTime);
        for (Map.Entry<String, Object> entry : changeMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            Field field = (Field) value;
            field.setAccessible(true); // 设置访问权限为可访问
            Object value1 = field.get(purchasing);
            Object value2 = field.get(purchasing1);
            if (key.equals("计划开始时间")) {
                if (!value1.equals(value2)) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format((Date) value1);
                    String format1 = simpleDateFormat.format((Date) value2);
                    map.put(key, format + "变更为" + format1);
                }
            } else if (key.equals("计划结束时间")) {
                if (!value1.equals(value2)) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format((Date) value1);
                    String format1 = simpleDateFormat.format((Date) value2);
                    map.put(key, format + "变更为" + format1);
                }
            } else {
                // 比较属性值是否相等
                if ((value1 != null && value2 != null && !value1.equals(value2))) {
                    if (value1 instanceof BigDecimal) {
                        BigDecimal val1 = (BigDecimal) value1;
                        BigDecimal val2 = (BigDecimal) value2;
                        if (val1.compareTo(val2) != 0) {
                            map.put(key, value1 + "变更为" + value2);
                        }
                    } else {
                        map.put(key, value1 + "变更为" + value2);
                    }
                }
            }
        }
        return map;
    }

    //项目主子列表查询
    @Override
    public List<Map> getProjectTree(ProjectInfo projectInfo, SubProjectInfo subProjectInfo) {
        List<ProjectInfo> fList = projectInfoMapper.selectProjectInfoList(projectInfo);
        List<SubProjectInfo> zList = subProjectInfoMapper.selectSubProjectInfoList(subProjectInfo);
        //List<MainType> fList=mainTypes.stream().filter(obj->obj.getParentId().equals("00000000-0000-0000-0000-000000000000")).collect(Collectors.toList());
        //List<MainType> zList=mainTypes.stream().filter(obj->!obj.getParentId().equals("00000000-0000-0000-0000-000000000000")).collect(Collectors.toList());
        List<Map> list = new ArrayList<>();
        for (ProjectInfo info : fList) {
            Map map = new HashMap<>();
            map.put("id", info.getProjectId());
            map.put("projectNumber", info.getProjectNumber());//项目编号
            map.put("projectName", info.getProjectName());//项目名称
            map.put("projectLeader", info.getProjectLeader());//项目负责人
            map.put("projectLeaderId", info.getProjectLeaderId());//项目负责人id
            map.put("executorName", info.getExecutorName());//执行人
            map.put("executorId", info.getExecutorId());//执行人id
            map.put("attackTime", info.getAttackTime());//项目启动时间
            map.put("completeTime", info.getCompleteTime());//项目完成时间
            map.put("startTime", info.getStartTime());//项目计划开始时间
            map.put("endTime", info.getEndTime());//项目计划结束时间
            map.put("state", info.getState());//项目状态
            map.put("sign", "主");//项目状态
            map.put("sumAmount", info.getSumAmount());//预算总额
            map.put("creationName", info.getCreationName());//创建人
            map.put("creationTime", info.getCreationTime());//创建时间
            List<Map> listMap = listSubProject(zList, info.getProjectId());
            if (listMap.size() != 0) {
                map.put("children", listMap);
            }
            list.add(map);
        }
        return list;
    }

    @Override
    public List<Map> getSubProjectTree(ProjectInfo projectInfo, SubProjectInfo subProjectInfo) {
        //只能查询自己公司的项目
        projectInfo.setBelongTo(SecurityUtils.getOrgId().toString());
        List<ProjectInfo> fList = projectInfoMapper.selectSubProjectInfoAllList(projectInfo);
        List<SubProjectInfo> infoList = subProjectInfoMapper.selectSubProjectInfoList(subProjectInfo);
        List<SubProjectInfo> zList = mergeSubProjectInfo(infoList);
        List<Map> list = new ArrayList<>();
        for (ProjectInfo info : fList) {
            Map map = new HashMap<>();
            map.put("id", info.getProjectId());
            map.put("projectNumber", info.getProjectNumber());//项目编号
            map.put("projectName", info.getProjectName());//项目名称
            map.put("projectLeader", info.getProjectLeader());//项目负责人
            map.put("attackTime", info.getAttackTime());//项目启动时间
            map.put("completeTime", info.getCompleteTime());//项目完成时间
            map.put("startTime", info.getStartTime());//项目计划开始时间
            map.put("endTime", info.getEndTime());//项目计划结束时间
            map.put("state", info.getState());//项目状态
            map.put("sign", "主");//项目状态
            map.put("contractReviewer", info.getContractReviewer());//项目状态
            map.put("budgetAmount", info.getBudgetAmount());//预算总额
            map.put("creationName", info.getCreationName());//创建人
            map.put("creationTime", info.getCreationTime());//创建时间
            List<Map> listMap = listSubProject(zList, info.getProjectId());
            if (listMap.size() != 0) {
                map.put("children", listMap);
            }
            list.add(map);
        }
        return list;
    }

    //子项目信息
    private List<Map> listSubProject(List<SubProjectInfo> infoList, String parentId) {
        List<Map> list = new ArrayList<>();
        List<SubProjectInfo> zList = mergeSubProjectInfo(infoList);
        for (SubProjectInfo info : zList) {
            if (info.getProjectId().equals(parentId)) {
                Map map = new HashMap<>();
                map.put("projectId", info.getProjectId());
                map.put("id", info.getId());
                map.put("projectNumber", info.getProjectNumber());//项目编号
                map.put("projectName", info.getProjectName());//项目名称
                map.put("startTime", info.getStartTime());//项目启动时间
                map.put("endTime", info.getEndTime());//项目完成时间
                map.put("type", info.getType());//类型
                map.put("sign", "子");//项目类型
                map.put("state", info.getState());//项目状态
                map.put("sumAmount", info.getCost());//费用
                map.put("executorId", info.getExecutorId());//执行人id
                map.put("executorName", info.getExecutorName());//项目执行人
                map.put("creationName", info.getCreationName());//创建人
                map.put("creationTime", info.getCreationTime());//创建时间
                list.add(map);
            }
        }
        return list;
    }

    //修改主分类
    @Override
    public int editMainClass(BusinessMainClassVo businessMainClassVo) {
        boolean flag = businessMainClassVo.getBusinessId().contains(",");
        int count = 0;
        if (flag) {
            String[] businessIds = businessMainClassVo.getBusinessId().split(",");
            for (int i = 0; i < businessIds.length; i++) {
                ProjectInfo info = projectInfoMapper.selectProjectInfoByProjectId(businessIds[i]);
                info.setClassificationId(businessMainClassVo.getMainClassId());
                info.setOperateTime(new Timestamp(new Date().getTime()));
                info.setOperateName(SecurityUtils.getUsername());
                info.setOperateId(SecurityUtils.getUserId().toString());
                count = projectInfoMapper.updateProjectInfo(info);
            }
        } else {
            ProjectInfo info = projectInfoMapper.selectProjectInfoByProjectId(businessMainClassVo.getBusinessId());
            info.setClassificationId(businessMainClassVo.getMainClassId());
            info.setOperateTime(new Timestamp(new Date().getTime()));
            info.setOperateName(SecurityUtils.getUsername());
            info.setOperateId(SecurityUtils.getUserId().toString());
            count = projectInfoMapper.updateProjectInfo(info);
        }
        return count;
    }

    //修改项目状态
    @Override
    public int editState(ProjectInfo projectInfo) {
        int count = 0;
        count = projectInfoMapper.editState(projectInfo);
        return count;
    }
    @Override
    public int editSubState(String subId,String subType) {
        int count = 0;
        SubProjectInfo subInfo = new SubProjectInfo();//子项目
        Purchasing purchasing = new Purchasing();//采购与合作
        subInfo.setId(subId);
        subInfo.setState("5");
        purchasing.setProjectId(subId);//终止
        purchasing.setStatus("6");//终止
        count = subProjectInfoMapper.updateSubProjectInfo(subInfo);
//        if(subType=="2"){//自营
//            count = subProjectInfoMapper.updateSubProjectInfo(subInfo);
//        }else{
//            count = purchasingMapper.updatePurchasingByProjectId(purchasing);
//        }
        return count;
    }


    /**
     * 查询项目信息
     *
     * @param projectId 项目信息主键
     * @return 项目信息
     */
    @Override
    public ProjectInfo selectProjectInfoByProjectId(String projectId) {
        ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoByProjectId(projectId);
        return projectInfo;
    }

    /**
     * 查询项目信息列表
     *
     * @param projectInfo 项目信息
     * @return projectInfo
     */
    @Override
    public List<ProjectInfo> selectProjectInfoList(ProjectInfo projectInfo) {
        return projectInfoMapper.selectProjectInfoList(projectInfo);
    }

    @Override
    public List<ProjectInfo> selectProjectInfoOtherList(ProjectInfo projectInfo) {
        projectInfo.setBelongTo(SecurityUtils.getOrgId().toString());
        return projectInfoMapper.selectProjectInfoOtherList(projectInfo);
    }

    @Override
    public List<ProjectInfo> selectProjectInfoListAll(ProjectInfo projectInfo) {
        projectInfo.setBelongTo(SecurityUtils.getOrgId().toString());
        return projectInfoMapper.selectProjectInfoListAll(projectInfo);
    }

    @Override
    public List<ProjectInfo> selectProjectInfoListOver(ProjectInfo projectInfo) {
        //新需求：项目负责人和入驻的企业可以进行查看和评价
        projectInfo.setEnterpriseId(SecurityUtils.getOrgId().toString());
        projectInfo.setProjectLeaderId(SecurityUtils.getUserId().toString());
        return projectInfoMapper.selectProjectInfoListOver(projectInfo);
    }
    @Override
    public List<ProjectInfo> selectSubProjectInfoAllList(ProjectInfo projectInfo) {
        if(SecurityUtils.getUserId()!=1&&SecurityUtils.getUserId()!=2){
            projectInfo.setBelongTo(SecurityUtils.getOrgId().toString());
        }
        return projectInfoMapper.selectSubProjectInfoAllList(projectInfo);
    }

    /**
     * 新增项目信息
     *
     * @param projectInfo 项目信息
     * @return 结果
     */
    @Override
    public int insertProjectInfo(ProjectInfo projectInfo) {
        projectInfo.setCreationTime(new Timestamp(new Date().getTime()));
        return projectInfoMapper.insertProjectInfo(projectInfo);
    }

    @Override
    public int selectProjectInfoNumber(String belongTo) {
        return projectInfoMapper.selectProjectInfoNumber(belongTo);
    }

    @Override
    public int selectProjectInfoIngNumber(String belongTo) {
        return projectInfoMapper.selectProjectInfoIngNumber(belongTo);
    }

    /**
     * 修改项目信息
     *
     * @param projectInfo 项目信息
     * @return 结果
     */
    @Override
    public int updateProjectInfo(ProjectInfo projectInfo) {
        if("yes".equals(projectInfo.getRecipientType())){
            SelfBuiltProject project = selfBuiltProjectMapper.selectSelfBuiltProjectByProjectId(projectInfo.getClassificationId());
            project.setStatus("0");
            selfBuiltProjectMapper.updateSelfBuiltProject(project);
            projectInfo.setState("0");
            return projectInfoMapper.updateProjectInfo(projectInfo);
        }else if("no".equals(projectInfo.getRecipientType())){
            SelfBuiltProject project = selfBuiltProjectMapper.selectSelfBuiltProjectByProjectId(projectInfo.getClassificationId());
            project.setStatus("8");
            projectInfoMapper.deleteProjectInfoByProjectId(projectInfo.getProjectId());
            return selfBuiltProjectMapper.updateSelfBuiltProject(project);
        }else{
            List<ProjectPaymentMethod> methods = projectInfo.getProjectPaymentMethods();
            Long count = projectInfoMapper.count(projectInfo.getProjectId());
            if (count == 0) {//新增
                projectInfo.setCreationId(SecurityUtils.getUserId().toString());
                projectInfo.setCreationName(SecurityUtils.getUsername());
                projectInfo.setCreationTime(new Timestamp(new Date().getTime()));
                projectInfo.setDelFlag("0");
                projectInfo.setState("0");//立项
                for (int i = 0; i < methods.size(); i++) {
                    ProjectPaymentMethod projectPaymentMethod = new ProjectPaymentMethod();
                    projectPaymentMethod.setPaymentId(methods.get(i).getPaymentId());
                    projectPaymentMethod.setProjectId(projectInfo.getProjectId());
                    projectPaymentMethod.setAmountCollected(methods.get(i).getAmountCollected());
                    projectPaymentMethod.setPaymentName(methods.get(i).getPaymentName());
                    projectPaymentMethod.setEstimatedCollectionTime(methods.get(i).getEstimatedCollectionTime());
                    projectPaymentMethodMapper.insertProjectPaymentMethod(projectPaymentMethod);
                }
            } else {//编辑
                projectInfo.setOperateId(SecurityUtils.getUserId().toString());
                projectInfo.setOperateName(SecurityUtils.getUsername());
                projectInfo.setOperateTime(new Timestamp(new Date().getTime()));
                if (methods!=null){
                    projectPaymentMethodMapper.deleteProjectPaymentMethodByProjectId(projectInfo.getProjectId());
                    for (int i = 0; i < methods.size(); i++) {
                        ProjectPaymentMethod projectPaymentMethod = new ProjectPaymentMethod();
                        projectPaymentMethod.setPaymentId(methods.get(i).getPaymentId());
                        projectPaymentMethod.setProjectId(projectInfo.getProjectId());
                        projectPaymentMethod.setAmountCollected(methods.get(i).getAmountCollected());
                        projectPaymentMethod.setPaymentName(methods.get(i).getPaymentName());
                        projectPaymentMethod.setEstimatedCollectionTime(methods.get(i).getEstimatedCollectionTime());
                        projectPaymentMethodMapper.insertProjectPaymentMethod(projectPaymentMethod);
                    }
                }
            }


            if (StringUtils.isNotEmpty(projectInfo.getProjectStage()) && StringUtils.isNotEmpty(projectInfo.getExecutorName())) {
                projectStageMapper.deleteProjectStageByProjectId(projectInfo.getProjectId());
                boolean flag = projectInfo.getProjectStage().contains("→");
                if(flag){
                    String[] stages = projectInfo.getProjectStage().split("→");
                    for (int i = 0; i < stages.length; i++) {
                        ProjectStage stage = new ProjectStage();
                        stage.setId(UUID.randomUUID().toString());
                        stage.setProjectId(projectInfo.getProjectId());
                        stage.setStageName(projectInfo.getProjectStage());
                        stage.setName(stages[i]);
                        stage.setSort(i);
                        stage.setState("0");
                        stage.setTemplateId(projectInfo.getCurrentTemplateId());
                        projectStageMapper.insertProjectStage(stage);
                    }
                }else{
                    ProjectStage stage = new ProjectStage();
                    stage.setId(UUID.randomUUID().toString());
                    stage.setProjectId(projectInfo.getProjectId());
                    stage.setStageName(projectInfo.getProjectStage());
                    stage.setName(projectInfo.getProjectStage());
                    stage.setSort(0);
                    stage.setState("0");
                    stage.setTemplateId(projectInfo.getCurrentTemplateId());
                    projectStageMapper.insertProjectStage(stage);
                }
            }

            projectInfo.setOrganizationId(SecurityUtils.getOrgId().toString());
            projectInfo.setOrganizationName(SecurityUtils.getOrgName());
            projectInfo.setDepartmentId(SecurityUtils.getDeptId().toString());

            projectInfo.setSign("0");
            ProjectInfo projectInfo1 = projectInfoMapper.selectProjectInfoByProjectId(projectInfo.getProjectId());
            if (Objects.isNull(projectInfo1)){
              projectInfo.setBelongTo(SecurityUtils.getOrgId().toString());
            }
            projectInfo.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
            //修改一下：根据客户名称查询客户是否入驻，如果入驻，存入的则是企业id
            if (Objects.nonNull(projectInfo.getEnterpriseName())) {
                SysDept sysDept = sysDeptMapper.selectByDeptName(projectInfo.getEnterpriseName());
                if (Objects.nonNull(sysDept)) {
                    projectInfo.setEnterpriseId(sysDept.getDeptId().toString());
                }
            }
            ProjectInfo info = projectInfoMapper.selecProjectInfoByProjectInfoId(projectInfo.getProjectId());
            if (Objects.nonNull(info)){
                projectInfo.setCovenantId(info.getCovenantId());
                projectInfo.setContractReviewer(info.getContractReviewer());
            }
            return count > 0 ? projectInfoMapper.updateProjectInfo(projectInfo) : this.insertProjectInfo(projectInfo);
        }
    }

    /**
     * 批量删除项目信息
     *
     * @param projectIds 需要删除的项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProjectInfoByProjectIds(String[] projectIds) {
        return projectInfoMapper.deleteProjectInfoByProjectIds(projectIds);
    }

    /**
     * 删除项目信息信息
     *
     * @param projectId 项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProjectInfoByProjectId(String projectId) {
        return projectInfoMapper.deleteProjectInfoByProjectId(projectId);
    }

    @Override
    public ProjectInfo selectProjectInfoByProjectIdAndContractId(String projectId) {
       return projectInfoMapper.selectProjectInfoByProjectIdAndContract(projectId);
    }

    @Override
    public List<ProjectInfo> selectProjectInfoWorkListList(ProjectInfo projectInfo) {
        projectInfo.setBelongTo(SecurityUtils.getOrgId().toString());
        return projectInfoMapper.selectProjectInfoWorkList(projectInfo);
    }

    private List<SubProjectInfo> mergeSubProjectInfo(List<SubProjectInfo> list) {
        Map<String, SubProjectInfo> map = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            String key = list.get(i).getProjectId()+list.get(i).getSubProjectStage()+list.get(i).getProductId();
            if (map.containsKey(key)) {
                list.get(i).setSubProjectStage(list.get(i).getSubProjectStage());
                map.put(key, list.get(i));
            } else {
                map.put(key, list.get(i));
            }
        }
        List<SubProjectInfo> subProjectInfos = new ArrayList<>();
        for (String key : map.keySet()) {
            subProjectInfos.add(map.get(key));
        }
        return subProjectInfos;
    }
}
